import 'package:cached_network_image/cached_network_image.dart';
import 'package:family_expense/features/account_user/services/user_service.dart';
import 'package:family_expense/features/account_user/widgets/user_avatar.dart';
import 'package:family_expense/features/account_user/widgets/user_shared.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

/// This is for display the current user basic info.
///
/// The previous version is using [MultiProvider], [FutureProvider], [ChangeNotifierProxyProvider] and [Consumer].
/// But the [StatefulWidget] works and makes the code cleaner.
/// Because the [build] is called during navigation. When comes back from editing page this page will be re-built.
/// When using provider the [FutureProvider] will be called many times during navigation. [initState] only called once.
class UserBasicInfo extends StatefulWidget {
  const UserBasicInfo(this.user, {super.key});

  final User user;

  @override
  State<UserBasicInfo> createState() => _UserBasicInfoState();
}

class _UserBasicInfoState extends State<UserBasicInfo> {
  final UserService _userService = UserService();
  final AuthStateService _authStateService = AuthStateService.instance;

  // User info retrieves from server by id.
  User? _user;

  @override
  void initState() {
    super.initState();

    // The user from argument does not contains all details.
    // That's why we need to query again.
    _queryDetails();
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      // We need to pass result back to previous page. So we are canceling the original pop.
      onPopInvokedWithResult: _onPopInvokedWithResult,
      child: Scaffold(
        appBar: AppBar(
          title: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text('基本信息'),
              if (_user?.isAccountGroupCreator == true)
                const Text('账户组注册人', style: TextStyle(fontSize: 10.0)),
            ],
          ),
        ),
        body: _buildBody(),
      ),
    );
  }

  /// Generates the user detail item list.
  Widget _buildBody() {
    if (_user == null) {
      return const MyPageTopCenterLoadingIndicator();
    }

    return ListView(
      children: [
        ListTile(
          title: const Text('用户名'),
          trailing: Text(_user!.username!.formatMobilePhoneNumber()),
        ),
        ListTile(
          title: const Text('角色'),
          trailing: Wrap(
            spacing: 8.0,
            runSpacing: 4.0,
            children: UserShared.buildUserdRoleChips(_user!),
          ),
        ),
        const Divider(),
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 10.0),
          child: SimpleDetailListTile(
            title: const Text('头像'),
            value: Hero(
              tag: _user!.id!,
              transitionOnUserGestures: true,
              child: ClipOval(
                child: CachedNetworkImage(
                  imageUrl: _user!.avatarUrl!,
                  width: 60.0,
                  height: 60.0,
                  fit: BoxFit.cover,
                ),
              ),
            ),
            onTap: () => NavigatorHelper.push(
              context,
              UserAvatar(_user!.id!, _user!.avatarUrl!, (value) async {
                if (mounted) {
                  // Triggers current page build to reflect the updated avatar.
                  setState(() => _user!.avatarUrl = value);
                }

                // Updates local data.
                final user = (await _authStateService.currentUser)!
                  ..avatarUrl = value;

                // Saves to local storage.
                _authStateService.saveUserInfo(user);

                // If user info exists in collection for quick login then we need to update it as well.
                if (await _authStateService.isUserInCollection(user)) {
                  _authStateService.saveUserToCollection(user);
                }

                // Updates the finaliable and it will be returned via navigation.
                _user = user;
              }),
            ),
          ),
        ),
        SimpleTextDetailListTile(
          title: '名称',
          value: _user!.fullName!,
          formTextFieldValidator: FormTextFieldValidator(
            null,
            null,
            maxLength: User.fullNameMaxLength,
          ),
          onConfirmed: (value) {
            if (mounted) {
              // Triggers build.
              setState(() => _user!.fullName = value);
            }

            // Updates the data to the server and local.
            _update(_user!);
          },
        ),
        Card(
          child: InkWell(
            onTap: () => NavigatorHelper.push(
              context,
              SingleInputField(
                title: '描述',
                initialValue: _user!.description ?? '',
                maxLines: null,
                formTextFieldValidator: FormTextFieldValidator(
                  null,
                  null,
                  isRequired: false,
                  maxLength: User.descriptionMaxLength,
                ),
                onConfirmed: (value) {
                  if (mounted) {
                    // Triggers build.
                    setState(() => _user!.description = value);
                  }

                  // Updates the data to the server and local.
                  _update(_user!);
                },
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const ListTile(
                  title: Text('描述'),
                  trailing: ListTileNavigateNextIcon(),
                ),
                if (_user!.description.isNotNullOrEmpty)
                  Padding(
                    padding: const EdgeInsets.only(
                      left: 15.0,
                      right: 15.0,
                      bottom: 15.0,
                    ),
                    child: Text(
                      _user!.description ?? '',
                      style: const TextStyle(color: Colors.black54),
                    ),
                  ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// Loads user details from server by id.
  Future<void> _queryDetails() async {
    final res = await _userService.queryDetails(widget.user.id!);

    if (mounted) {
      setState(() => _user = res);
    }
  }

  /// Checks the data before popping.
  void _onPopInvokedWithResult(bool didPop, dynamic result) {
    if (didPop) {
      return;
    }

    // Passes the update indicator to previous page for refresh.
    NavigatorHelper.pop<User>(context, _user);
  }

  /// Updates the data to the server and local.
  Future<void> _update(User user) async {
    // Updates the user avatar to the server.
    await _userService.updateCurrentUser(user);

    // Saves to local storage.
    _authStateService.saveUserInfo(user);

    // If user info exists in collection for quick login then we need to update it as well.
    if (await _authStateService.isUserInCollection(user)) {
      _authStateService.saveUserToCollection(user);
    }
  }
}
